from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                            QSpinBox, QCheckBox, QPushButton, QLineEdit,
                            QProgressBar, QGroupBox, QFormLayout)
from PyQt6.QtCore import Qt, QSettings
from PyQt6.QtGui import QFont, QIcon
from password_generator import PasswordGenerator

class PasswordGeneratorDialog(QDialog):
    """密码生成器对话框"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.settings = QSettings('PasswordManager', 'Settings')
        self.password_generator = PasswordGenerator()
        self.init_ui()
        self.load_settings()
        self.apply_styles()
        
        # 生成初始密码
        self.generate_password()
    
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("密码生成器")
        self.setMinimumWidth(450)
        
        # 主布局
        layout = QVBoxLayout()
        layout.setSpacing(15)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 密码显示区域
        password_group = QGroupBox("生成的密码")
        password_layout = QHBoxLayout()
        
        self.password_edit = QLineEdit()
        self.password_edit.setReadOnly(True)
        self.password_edit.setMinimumHeight(40)
        password_layout.addWidget(self.password_edit)
        
        self.copy_btn = QPushButton()
        self.copy_btn.setIcon(QIcon("icons/copy.png"))  # 需要添加图标
        self.copy_btn.setToolTip("复制到剪贴板")
        self.copy_btn.clicked.connect(self.copy_password)
        password_layout.addWidget(self.copy_btn)
        
        self.refresh_btn = QPushButton()
        self.refresh_btn.setIcon(QIcon("icons/refresh.png"))  # 需要添加图标
        self.refresh_btn.setToolTip("重新生成")
        self.refresh_btn.clicked.connect(self.generate_password)
        password_layout.addWidget(self.refresh_btn)
        
        password_group.setLayout(password_layout)
        layout.addWidget(password_group)
        
        # 密码强度指示器
        strength_group = QGroupBox("密码强度")
        strength_layout = QVBoxLayout()
        
        self.strength_progress = QProgressBar()
        self.strength_progress.setTextVisible(True)
        self.strength_progress.setRange(0, 100)
        strength_layout.addWidget(self.strength_progress)
        
        self.strength_label = QLabel()
        strength_layout.addWidget(self.strength_label)
        
        strength_group.setLayout(strength_layout)
        layout.addWidget(strength_group)
        
        # 选项设置
        options_group = QGroupBox("生成选项")
        options_layout = QFormLayout()
        
        # 密码长度
        length_layout = QHBoxLayout()
        self.length_spin = QSpinBox()
        self.length_spin.setRange(4, 64)
        self.length_spin.valueChanged.connect(self.generate_password)
        length_layout.addWidget(self.length_spin)
        
        options_layout.addRow("密码长度:", length_layout)
        
        # 字符类型选项
        self.uppercase_check = QCheckBox("大写字母 (A-Z)")
        self.uppercase_check.stateChanged.connect(self.generate_password)
        options_layout.addRow(self.uppercase_check)
        
        self.lowercase_check = QCheckBox("小写字母 (a-z)")
        self.lowercase_check.stateChanged.connect(self.generate_password)
        options_layout.addRow(self.lowercase_check)
        
        self.numbers_check = QCheckBox("数字 (0-9)")
        self.numbers_check.stateChanged.connect(self.generate_password)
        options_layout.addRow(self.numbers_check)
        
        self.symbols_check = QCheckBox("特殊符号 (!@#$...)")
        self.symbols_check.stateChanged.connect(self.generate_password)
        options_layout.addRow(self.symbols_check)
        
        self.similar_check = QCheckBox("排除相似字符 (1, l, I, 0, O)")
        self.similar_check.stateChanged.connect(self.generate_password)
        options_layout.addRow(self.similar_check)
        
        options_group.setLayout(options_layout)
        layout.addWidget(options_group)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.setObjectName("cancelButton")
        self.cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_btn)
        
        self.use_btn = QPushButton("使用此密码")
        self.use_btn.setObjectName("primaryButton")
        self.use_btn.clicked.connect(self.accept)
        button_layout.addWidget(self.use_btn)
        
        layout.addLayout(button_layout)
        
        self.setLayout(layout)
    
    def load_settings(self):
        """从QSettings加载设置"""
        self.length_spin.setValue(self.settings.value('password_length', 16, type=int))
        self.uppercase_check.setChecked(self.settings.value('include_uppercase', True, type=bool))
        self.lowercase_check.setChecked(self.settings.value('include_lowercase', True, type=bool))
        self.numbers_check.setChecked(self.settings.value('include_numbers', True, type=bool))
        self.symbols_check.setChecked(self.settings.value('include_symbols', True, type=bool))
        self.similar_check.setChecked(self.settings.value('exclude_similar', False, type=bool))
    
    def save_settings(self):
        """保存设置到QSettings"""
        self.settings.setValue('password_length', self.length_spin.value())
        self.settings.setValue('include_uppercase', self.uppercase_check.isChecked())
        self.settings.setValue('include_lowercase', self.lowercase_check.isChecked())
        self.settings.setValue('include_numbers', self.numbers_check.isChecked())
        self.settings.setValue('include_symbols', self.symbols_check.isChecked())
        self.settings.setValue('exclude_similar', self.similar_check.isChecked())
        self.settings.sync()
    
    def generate_password(self):
        """生成新密码并更新界面"""
        # 生成密码
        password = self.password_generator.generate_password(
            length=self.length_spin.value(),
            include_uppercase=self.uppercase_check.isChecked(),
            include_lowercase=self.lowercase_check.isChecked(),
            include_numbers=self.numbers_check.isChecked(),
            include_symbols=self.symbols_check.isChecked(),
            exclude_similar=self.similar_check.isChecked()
        )
        
        self.password_edit.setText(password)
        
        # 检查密码强度
        score, strength, suggestions = self.password_generator.check_password_strength(password)
        
        # 更新强度指示器
        self.strength_progress.setValue(score)
        self.strength_progress.setStyleSheet(self._get_progress_style(score))
        
        # 更新强度标签
        if suggestions:
            self.strength_label.setText(f"强度: {strength} - {'; '.join(suggestions)}")
        else:
            self.strength_label.setText(f"强度: {strength}")
    
    def copy_password(self):
        """复制密码到剪贴板"""
        if self.password_edit.text():
            clipboard = self.clipboard()
            clipboard.setText(self.password_edit.text())
            
            # 如果设置了自动清除剪贴板
            clear_time = self.settings.value('clear_clipboard', 10, type=int)
            if clear_time > 0:
                QTimer.singleShot(clear_time * 1000, lambda: clipboard.clear())
    
    def accept(self):
        """保存设置并关闭对话框"""
        self.save_settings()
        super().accept()
    
    def _get_progress_style(self, score):
        """根据分数返回进度条样式"""
        if score < 40:
            color = "#fa5252"  # 红色
        elif score < 60:
            color = "#ffd43b"  # 黄色
        elif score < 80:
            color = "#51cf66"  # 浅绿色
        else:
            color = "#40c057"  # 深绿色
            
        return f"""
            QProgressBar {{
                border: 1px solid #ced4da;
                border-radius: 8px;
                text-align: center;
                background-color: #f8f9fa;
            }}
            
            QProgressBar::chunk {{
                background-color: {color};
                border-radius: 7px;
            }}
        """
    
    def apply_styles(self):
        """应用样式到对话框"""
        self.setStyleSheet("""
            QDialog {
                background-color: #f8f9fa;
                border-radius: 15px;
            }
            
            QGroupBox {
                font-weight: bold;
                border: 1px solid #e9ecef;
                border-radius: 8px;
                margin-top: 12px;
                padding-top: 24px;
                background-color: white;
            }
            
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top left;
                left: 12px;
                padding: 0 5px;
                color: #495057;
                background-color: white;
            }
            
            QLineEdit {
                padding: 8px;
                border: 1px solid #ced4da;
                border-radius: 6px;
                background-color: white;
                font-family: monospace;
                font-size: 16px;
            }
            
            QLineEdit:focus {
                border-color: #4dabf7;
                box-shadow: 0 0 0 3px rgba(77, 171, 247, 0.25);
            }
            
            QPushButton {
                border-radius: 6px;
                padding: 8px;
                min-width: 32px;
            }
            
            QPushButton:hover {
                background-color: #e9ecef;
            }
            
            QSpinBox {
                padding: 6px;
                border: 1px solid #ced4da;
                border-radius: 6px;
                background-color: white;
            }
            
            QSpinBox:focus {
                border-color: #4dabf7;
                box-shadow: 0 0 0 3px rgba(77, 171, 247, 0.25);
            }
            
            QCheckBox {
                spacing: 8px;
                color: #495057;
            }
            
            QCheckBox::indicator {
                width: 18px;
                height: 18px;
                border-radius: 4px;
                border: 1px solid #ced4da;
            }
            
            QCheckBox::indicator:unchecked {
                background-color: white;
            }
            
            QCheckBox::indicator:checked {
                background-color: #4dabf7;
                border-color: #4dabf7;
            }
            
            QCheckBox::indicator:hover {
                border-color: #339af0;
            }
            
            QLabel {
                color: #495057;
            }
            
            #primaryButton {
                background-color: #4dabf7;
                color: white;
                border: none;
                padding: 10px 20px;
                font-weight: bold;
                font-size: 14px;
            }
            
            #primaryButton:hover {
                background-color: #339af0;
            }
            
            #primaryButton:pressed {
                background-color: #228be6;
            }
            
            #cancelButton {
                background-color: #f8f9fa;
                color: #495057;
                border: 1px solid #ced4da;
                padding: 10px 20px;
                font-size: 14px;
            }
            
            #cancelButton:hover {
                background-color: #e9ecef;
                border-color: #adb5bd;
            }
            
            #cancelButton:pressed {
                background-color: #dee2e6;
            }
        """)